package com.qianda.qdminiapp.controller.remote;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qianda.qdminiapp.common.constant.CommonConstant;
import com.qianda.qdminiapp.common.exception.ExceptionCode;
import com.qianda.qdminiapp.common.exception.SimpleException;
import com.qianda.qdminiapp.common.future.CommandFuture;
import com.qianda.qdminiapp.common.future.SendData;
import com.qianda.qdminiapp.common.rabbitmq.MsgProducer;
import com.qianda.qdminiapp.config.CompanyProperties;
import com.qianda.qdminiapp.controller.Result;
import com.qianda.qdminiapp.domain.dto.DeivceRegisterDto;
import com.qianda.qdminiapp.domain.dto.DeviceReadTimeOutDto;
import com.qianda.qdminiapp.domain.dto.DeviceStatusUploadDto;
import com.qianda.qdminiapp.domain.dto.OrderReturnDto;
import com.qianda.qdminiapp.domain.model.device.Device;
import com.qianda.qdminiapp.domain.model.device.QqdDevice;
import com.qianda.qdminiapp.service.DeviceService;
import com.qianda.qdminiapp.service.QqdDeviceService;
import com.qianda.qdminiapp.service.QqdOrderTowelService;
import com.qianda.qdminiapp.service.order.BalancePaymentImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName RemoteController
 * @Author cw
 * @Date 2019/8/12 11:27
 * @Version 1.0
 */
@RestController
@RequestMapping("/remote/v1")
@EnableConfigurationProperties({ CompanyProperties.class })
public class RemoteController {

    @Autowired
    private DeviceService deviceService;
    
    @Autowired
    private QqdDeviceService qqdDeviceService;

    @Autowired
    private QqdOrderTowelService qqdOrderTowelService;

    @Autowired
    private CompanyProperties companyProperties;

    @Autowired
    private MsgProducer msgProducer;

    private static Logger LOGGER = LoggerFactory.getLogger(RemoteController.class);

    /*
     * 设备注册
     * @Description
     * @Author cw
     * @Date 11:34 2019/8/12
     * @Param [deivceRegisterDto]
     * @return com.qianda.qdminiapp.controller.Result
     **/
    @PostMapping("/deviceRegister")
    public Result deviceRegister(@RequestBody  DeivceRegisterDto deivceRegisterDto){
        LOGGER.info("<<设备注册>> -- 开始进行注册请求");
        QueryWrapper<QqdDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("imei", deivceRegisterDto.getImei());
        queryWrapper.eq("status",CommonConstant.Status.STATUS_NORMAL);
        queryWrapper.eq("company_id",companyProperties.getId());

        QqdDevice device = qqdDeviceService.getOne(queryWrapper);
        if(device != null){
            LOGGER.info("<<设备注册>> -- 注册成功");
            qqdDeviceService.updateOnline(device.getId(),CommonConstant.DeviceOnline.DEVICE_ONLINE_YES);
            device.setDeviceOnline(CommonConstant.DeviceOnline.DEVICE_ONLINE_YES);
            //登录成功后对时
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //查询信号
                    Integer  sign = 0;
                    try{
                        sign =  qqdDeviceService.findSign(deivceRegisterDto.getImei());
                        device.setDeviceSign(sign);
                        qqdDeviceService.updateById(device);
                        LOGGER.info("信号值为:" + sign);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }, 5000);

            return Result.success(device.getDeviceCount());
        }else{
            LOGGER.info("<<设备注册>> -- 注册失败");
            return Result.failure(ExceptionCode.EX_HTTP_INPUT_NOT_ENTATY.code(),ExceptionCode.EX_HTTP_INPUT_NOT_ENTATY.message());
        }
    }

    @PostMapping("/deviceStatus")
    public Result deviceStatus(DeviceStatusUploadDto  deviceStatusUploadDto){

        return null;
    }

    /*
     * 出巾成功指令返回
     * @Description
     * @Author cw
     * @Date 9:08 2019/8/14
     * @Param []
     * @return com.qianda.qdminiapp.controller.Result
     **/
    @PostMapping("/outTowelReturn")
    public Result outTowelReturn(@RequestBody  OrderReturnDto orderReturnDto){
        qqdOrderTowelService.orderRemoteReturn(orderReturnDto);
        return  Result.success();
    }

    /*
     * 出巾异常指令返回
     * @Description
     * @Author cw
     * @Date 9:08 2019/8/14
     * @Param []
     * @return com.qianda.qdminiapp.controller.Result
     **/
    @PostMapping("/outTowelErrrorReturn")
    public Result outTowelErrorReturn(@RequestBody  OrderReturnDto orderReturnDto){
        qqdOrderTowelService.orderRemoteErrorReturn(orderReturnDto);
        return  Result.success();
    }

    /*
     * 设备毛巾数量更新
     * @Description
     * @Author cw
     * @Date 11:34 2019/8/12
     * @Param [deivceRegisterDto]
     * @return com.qianda.qdminiapp.controller.Result
     **/
    @PostMapping("/deviceCount")
    public Result deviceCount(@RequestBody  DeivceRegisterDto deivceRegisterDto){
        LOGGER.info("<<设备数量更新>> -- 开始进行数量请求");
        QueryWrapper<QqdDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("imei", deivceRegisterDto.getImei());

        QqdDevice device = qqdDeviceService.getOne(queryWrapper);
        //修改设备库存为初始值
        device.setDeviceCount(device.getDeviceBeginCount());
        qqdDeviceService.updateById(device);

        if(device != null){
            LOGGER.info("<<设备数量更新>> -- 请求成功");
            return Result.success(device.getDeviceBeginCount());
        }else{
            LOGGER.info("<<设备数量更新>> -- 请求失败");
            return Result.failure(ExceptionCode.EX_HTTP_INPUT_NOT_ENTATY.code(),ExceptionCode.EX_HTTP_INPUT_NOT_ENTATY.message());
        }
    }

    /*
     * 设备读超时
     * @Description
     * @Author cw
     * @Date 9:48 2019/9/2
     * @Param [deviceReadTimeOutDto]
     * @return com.qianda.qdminiapp.controller.Result
     **/
    @PostMapping("/readTimeOut")
    public Result readTimeOut(@RequestBody DeviceReadTimeOutDto deviceReadTimeOutDto){
        QueryWrapper<QqdDevice> qqdDeviceQueryWrapper = new QueryWrapper<>();
        qqdDeviceQueryWrapper.eq("imei",deviceReadTimeOutDto.getImei());
        qqdDeviceQueryWrapper.eq("status",CommonConstant.Status.STATUS_NORMAL);
        QqdDevice qqdDevice = qqdDeviceService.getOne(qqdDeviceQueryWrapper);

        //查询信号
        Integer  sign = 0;
        try{
             sign =  qqdDeviceService.findSign(deviceReadTimeOutDto.getImei());
             if(sign == 0){
                 LOGGER.info("设备查询信号不成功，超时处理");
                 qqdDeviceService.updateOnline(qqdDevice.getId(),CommonConstant.DeviceOnline.DEVICE_ONLINE_NO);
                 return Result.success();
             }else{
                 qqdDevice.setDeviceSign(sign);
                 qqdDeviceService.updateById(qqdDevice);
             }

        }catch (Exception e){
            e.printStackTrace();
        }
        LOGGER.info("设备查询信号成功，超时不处理");
        throw new SimpleException(ExceptionCode.EX_TIME_OUT_HANDLER_ERROR);
    }


}
